package com.organization
import grails.converters.JSON
import org.codehaus.groovy.grails.exceptions.GrailsException

class DataController {

    def localDataService

    def index = {
        render ""
    }

    //get tree structure for treepanel element of ExtJs framework
    def getTree = {
        render localDataService.getBranch(params.node) as JSON
    }

    //get organization name for GUI
    def getTitle = {
        render localDataService.getOrganizationInfo() as JSON
    }

    //get all node fields
	def getElement = {
        render localDataService.getElement(params.nodeId) as JSON
    }

    //update node
    def update = {
        render localDataService.updateElement(params.nodeId, paramsToMap(params)) as JSON
    }

    //add new child node to selected parent node
    def add = {
        render localDataService.addElement(params.parentNodeId,paramsToMap(params)) as JSON
    }

    //delete node
    def delete = {
        render localDataService.deleteElement(params.nodeId,paramsToMap(params)) as JSON
    }

    //convert GrailsParameterMap to Map
    private Map paramsToMap(def params){
        Map result = [:]
        Iterator it = params.entrySet().iterator()
        while (it.hasNext()) {
            Map.Entry pairs = (Map.Entry)it.next()
            result.putAt(pairs.getKey(),pairs.getValue())
        }
        return result
    }
}
